package org.csu.lestore.api.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import org.csu.lestore.api.common.CommonResponse;
import org.csu.lestore.api.entity.*;
import org.csu.lestore.api.service.CatalogService;
import org.csu.lestore.api.util.RandomUtils;
import org.csu.lestore.api.vo.AccountVO;
import org.csu.lestore.api.vo.CategoryVO;
import org.csu.lestore.api.vo.ItemVO;
import org.csu.lestore.api.vo.ProductVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/catalog/")
public class CatalogController {
    private static Logger logger = LoggerFactory.getLogger(CatalogController.class);

    @Autowired
    CatalogService catalogService;

    @GetMapping( "categories")//获取全部category
    @ResponseBody
    public CommonResponse<IPage<CategoryVO>> getCategoryList(@RequestParam("size") int size, @RequestParam("curPage") int curPage){
        return catalogService.getCategoryListInPage(curPage,size);
    }

    @GetMapping("categories/{categoryId}")//根据id获取category信息
    @ResponseBody
    public CommonResponse<CategoryVO> getCategory(@PathVariable("categoryId") int categoryId){
        return catalogService.getCategoryById(categoryId);
    }

    @GetMapping("categories/{categoryId}/products")//根据categoryid获取category下product信息
    @ResponseBody
    public CommonResponse<IPage<ProductVO>> getProductByCategoryId(@PathVariable("categoryId") int categoryId,
                                                                   @RequestParam("size") int size,
                                                                   @RequestParam("curPage") int curPage){
        return catalogService.getProductListInPageByCategoryId(curPage,size,categoryId);
    }

    @GetMapping("products")//获取全部product
    @ResponseBody
    public CommonResponse<IPage<ProductVO>> getProduct(@RequestParam("size") int size,
                                                       @RequestParam("curPage") int curPage){
        return catalogService.getProductListInPage(curPage,size);
    }

    @GetMapping("products/{productId}")//根据id获取product信息
    @ResponseBody
    public CommonResponse<ProductVO> getProduct(@PathVariable("productId") int productId,HttpSession session){
        AccountVO login_accountVO = (AccountVO) session.getAttribute("login_account");
        if (login_accountVO!=null) {
            Fav fav = catalogService.getFavProduct(login_accountVO.getUserId(), productId).getData();
            String msg = "";
            if(fav!=null){//判断当前账号是否收藏了该product
                msg = "已收藏";
            }else{
                msg = "未收藏";
            }
            return CommonResponse.createForSuccess(msg,catalogService.getProductById(productId).getData());
        }
        else{
            return CommonResponse.createForSuccess("未登录",catalogService.getProductById(productId).getData());
        }
    }

    @GetMapping("products/{productId}/items")//根据productid获取product下item信息
    @ResponseBody
    public CommonResponse<IPage<ItemVO>> getItemsByProductId(@PathVariable("productId") int productId,@RequestParam("size") int size, @RequestParam("curPage") int curPage){
        return catalogService.getItemsInPageByProductId(curPage,size,productId);
    }


    @GetMapping("items/{itemId}")//根据id获取item信息
    @ResponseBody
    public CommonResponse<ItemVO> viewItemDetail(@PathVariable("itemId") int itemId){
        return catalogService.getItemByItemId(itemId);
    }

    @GetMapping("search_products")//根据productName进行搜索
    @ResponseBody
    public CommonResponse<IPage<ProductVO>> searchProduct(@RequestParam("keyword") String keyword,@RequestParam("size") int size, @RequestParam("curPage") int curPage){
        return catalogService.getProductByName(curPage,size,keyword);
    }

    @GetMapping("search_item")//根据attr进行搜索
    @ResponseBody
    public CommonResponse<ItemVO> searchItem(@RequestParam("productId") int productId,
                                             @RequestParam("attr1") String attr1,
                                             @RequestParam("attr2") String attr2,
                                             @RequestParam("attr3") String attr3){
        return catalogService.getItemByAttr(productId,attr1,attr2,attr3);
    }

    @PostMapping("insert_category")//新建category
    @ResponseBody
    public CommonResponse<CategoryVO> insertCategory(@RequestBody CategoryVO categoryVO,HttpSession session){
        AccountVO login_accountVO = (AccountVO) session.getAttribute("login_account");
        if (login_accountVO!=null&&login_accountVO.getStatus()=='M') {//要求管理员权限
            return catalogService.insertCategory(categoryVO);
        }
        else{
            return CommonResponse.createForError("未登录或权限不足");
        }

    }

    @PostMapping("insert_product")//新增product
    @ResponseBody
    public CommonResponse<Product> insertProduct(@RequestBody Product product,HttpSession session){
        AccountVO login_accountVO = (AccountVO) session.getAttribute("login_account");
        if (login_accountVO!=null&&(login_accountVO.getStatus()=='M'||login_accountVO.getStatus()=='S')) {//要求管理员或商户权限
            return catalogService.insertProduct(product);
        }
        else{
            return CommonResponse.createForError("未登录或权限不足");
        }
    }

    @PostMapping("insert_item")//新建item
    @ResponseBody
    public CommonResponse<ItemVO> insertItem(@RequestBody ItemVO itemVO,HttpSession session){
        AccountVO login_accountVO = (AccountVO) session.getAttribute("login_account");
        if (login_accountVO!=null&&login_accountVO.getStatus()=='M'||login_accountVO.getStatus()=='S') {//要求管理员或商户权限
            return catalogService.insertItem(itemVO);
        }
        else{
            return CommonResponse.createForError("未登录或权限不足");
        }

    }

    @PostMapping("update_category")//修改category
    @ResponseBody
    public CommonResponse<Category> updateCategory(@RequestBody Category category,HttpSession session){
        AccountVO login_accountVO = (AccountVO) session.getAttribute("login_account");
        if (login_accountVO!=null&&login_accountVO.getStatus()=='M'||login_accountVO.getStatus()=='S') {//要求管理员或商户权限
            return catalogService.updateCategory(category);
        }
        else{
            return CommonResponse.createForError("未登录或权限不足");
        }

    }

    @PostMapping("update_product")//修改product
    @ResponseBody
    public CommonResponse<Product> updateProduct(@RequestBody Product product,HttpSession session){
        AccountVO login_accountVO = (AccountVO) session.getAttribute("login_account");
        if (login_accountVO!=null&&login_accountVO.getStatus()=='M'||login_accountVO.getStatus()=='S') {//要求管理员或商户权限
            return catalogService.updateProduct(product);
        }
        else{
            return CommonResponse.createForError("未登录或权限不足");
        }

    }

    @PostMapping("update_item")//修改item
    @ResponseBody
    public CommonResponse<Item> updateItem(@RequestBody Item item,HttpSession session){
        AccountVO login_accountVO = (AccountVO) session.getAttribute("login_account");
        if (login_accountVO!=null&&login_accountVO.getStatus()=='M'||login_accountVO.getStatus()=='S') {//要求管理员或商户权限
            return catalogService.updateItem(item);
        }
        else{
            return CommonResponse.createForError("未登录或权限不足");
        }

    }

    @PostMapping("delete_category")//删除Category
    @ResponseBody
    public CommonResponse<Category> deleteCategory(@RequestParam("categoryId") int categoryId){
        return catalogService.deleteCategory(categoryId);
    }

    @PostMapping("delete_product")//删除Product
    @ResponseBody
    public CommonResponse<Product> deleteProduct(@RequestParam("productId") int productId){
        return catalogService.deleteProduct(productId);
    }

    @PostMapping("delete_item")//删除Item
    @ResponseBody
    public CommonResponse<Item> deleteItem(@RequestParam("itemId") int itemId){
        return catalogService.deleteItem(itemId);
    }

    @ResponseBody
    @PostMapping("saveProductImg")//上传、储存、设置图片
    public CommonResponse<Img> saveProductImg(@RequestParam MultipartFile file ,
                                              @RequestParam String productId  ,
                                              HttpSession session)throws IOException {
        String filePath=System.getProperty("user.dir")+"\\src\\main\\resources\\static\\images\\";
        filePath +="product\\";

        File pathFile=new File(filePath);
        if(!pathFile.exists()){
            pathFile.mkdirs();
        }

        //获得原始图片的拓展名
//        String originalFileName=file.getOriginalFilename();
        //新的文件名字
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateStr= formatter.format(date);

        String newFileName  =dateStr+ RandomUtils.randomNumberString(6);

        //封装上传文件位置的全路径
        File targetFile=new File(filePath,newFileName);
        //把本地文件上传到封装上传文件位置的全路径
        file.transferTo(targetFile);
        //设置图片路径，为字符串类型
        //插入数据库 img src : pathFile  user id ->  img
        Img img = new Img();
        img.setProductId(Integer.parseInt(productId));
        img.setImgSrc(newFileName);
        return catalogService.setProductImg(img);
    }

    @ResponseBody
    @PostMapping("saveCategoryImg")//上传、储存、设置图片
    public CommonResponse<CategoryVO> saveCategoryImg(@RequestParam MultipartFile file ,
                                              @RequestParam String categoryId  ,
                                              HttpSession session)throws IOException {
        String filePath=System.getProperty("user.dir")+"\\src\\main\\resources\\static\\images\\";
        filePath +="category\\";

        File pathFile=new File(filePath);
        if(!pathFile.exists()){
            pathFile.mkdirs();
        }

        //获得原始图片的拓展名
//        String originalFileName=file.getOriginalFilename();
        //新的文件名字
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateStr= formatter.format(date);

        String newFileName  =dateStr+ RandomUtils.randomNumberString(6);

        //封装上传文件位置的全路径
        File targetFile=new File(filePath,newFileName);
        //把本地文件上传到封装上传文件位置的全路径
        file.transferTo(targetFile);
        //设置图片路径，为字符串类型
        //插入数据库 img src : pathFile  user id ->  img
        return catalogService.setCategoryImg(Integer.parseInt(categoryId),newFileName);
    }

    @ResponseBody
    @PostMapping("saveItemImg")//上传、储存、设置图片
    public CommonResponse<ItemVO> saveItemImg(@RequestParam MultipartFile file ,
                                                      @RequestParam String itemId  ,
                                                      HttpSession session)throws IOException {
        String filePath=System.getProperty("user.dir")+"\\src\\main\\resources\\static\\images\\";
        filePath +="item\\";

        File pathFile=new File(filePath);
        if(!pathFile.exists()){
            pathFile.mkdirs();
        }

        //获得原始图片的拓展名
//        String originalFileName=file.getOriginalFilename();
        //新的文件名字
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateStr= formatter.format(date);

        String newFileName  =dateStr+ RandomUtils.randomNumberString(6);

        //封装上传文件位置的全路径
        File targetFile=new File(filePath,newFileName);
        //把本地文件上传到封装上传文件位置的全路径
        file.transferTo(targetFile);
        //设置图片路径，为字符串类型
        //插入数据库 img src : pathFile  user id ->  img
        return catalogService.setItemImg(Integer.parseInt(itemId),newFileName);
    }

    @GetMapping("favProduct")//获取登陆账号的收藏
    @ResponseBody
    public CommonResponse<IPage<ProductVO>> getFavProducts(HttpSession session){
        AccountVO login_accountVO = (AccountVO) session.getAttribute("login_account");
        if (login_accountVO!=null) {
            return catalogService.getFavProductListInPageByUserId(1,2147483647,login_accountVO.getUserId());
        }
        else{
            return CommonResponse.createForError("未登录");
        }
    }

    @GetMapping("searchFavProduct")//搜索收藏商品
    @ResponseBody
    public CommonResponse<IPage<ProductVO>> searchFavProducts(String keyword,HttpSession session){
        AccountVO login_accountVO = (AccountVO) session.getAttribute("login_account");
        if (login_accountVO!=null) {
            return catalogService.getFavProductListInPageByUserIdAndKeyword(1,2147483647,login_accountVO.getUserId(),keyword);
        }
        else{
            return CommonResponse.createForError("未登录");
        }
    }

    @PostMapping("addFavProduct")//添加收藏
    @ResponseBody
    public CommonResponse<Fav> addFavProduct(int productId,HttpSession session){
        AccountVO login_accountVO = (AccountVO) session.getAttribute("login_account");
        if (login_accountVO!=null) {
            Fav fav = new Fav();
            fav.setUserId(login_accountVO.getUserId());
            fav.setProductId(productId);
            return catalogService.setFavProduct(fav);
        }
        else{
            return CommonResponse.createForError("未登录");
        }

    }

    @PostMapping("removeFavProduct")//移除收藏
    @ResponseBody
    public CommonResponse<Fav> removeFavProduct(int productId,HttpSession session){
        AccountVO login_accountVO = (AccountVO) session.getAttribute("login_account");
        if (login_accountVO!=null) {
            Fav fav = new Fav();
            fav.setUserId(login_accountVO.getUserId());
            fav.setProductId(productId);
            return catalogService.deleteFavProduct(fav);
        }
        else{
            return CommonResponse.createForError("未登录");
        }

    }

    @PostMapping("addBrowseRecord")//浏览记录
    @ResponseBody
    public CommonResponse<Browse> addBrowseRecord(int productId,HttpSession session){
        AccountVO login_accountVO = (AccountVO) session.getAttribute("login_account");
        if (login_accountVO!=null) {
            return catalogService.insertBrowseRecord(login_accountVO.getUserId(),productId);
        }
        else{
            return CommonResponse.createForError("未登录");
        }
    }

    @PostMapping("removeBrowseRecord")//删除记录
    @ResponseBody
    public CommonResponse<Browse> removeBrowseRecord(int productId,HttpSession session){
        AccountVO login_accountVO = (AccountVO) session.getAttribute("login_account");
        if (login_accountVO!=null) {
            return catalogService.deleteBrowseRecord(login_accountVO.getUserId(),productId);
        }
        else{
            return CommonResponse.createForError("未登录");
        }
    }

    @PostMapping("removeAllBrowseRecord")//全部删除
    @ResponseBody
    public CommonResponse<Browse> removeAllBrowseRecord(HttpSession session){
        AccountVO login_accountVO = (AccountVO) session.getAttribute("login_account");
        if (login_accountVO!=null) {
            return catalogService.deleteAllBrowseRecordsByUserId(login_accountVO.getUserId());
        }
        else{
            return CommonResponse.createForError("未登录");
        }
    }

    @GetMapping("getAllBrowseRecords")//获取浏览记录
    @ResponseBody
    public CommonResponse<IPage<ProductVO>> getAllBrowseRecord(@RequestParam("size") int size,
                                                            @RequestParam("curPage") int curPage,
                                                            HttpSession session){
        AccountVO login_accountVO = (AccountVO) session.getAttribute("login_account");
        if (login_accountVO!=null) {
            return catalogService.getAllBrowseRecordsByUserId(curPage,size,login_accountVO.getUserId());
        }
        else{
            return CommonResponse.createForError("未登录");
        }
    }
}
